import React, { useEffect, useRef, useState } from 'react'
import {
  Card,
  Tabs,
  Table,
  Tag,
  Typography,
  Space,
  Pagination,
  Input,
  Button,
} from 'antd'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  PhoneOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import styles from './index.module.less'
import { P1AlarmInfo } from '@/service/api'
import { Tab_status } from '@/config/env'
import UseList from '@/hooks/getList'
import { useTableContext } from '@/contexts/TableContext'
import { TableType } from '@/config/types'

const { Title } = Typography
const { TabPane } = Tabs

const TableList: React.FC<{
  type: TableType
  listData: P1AlarmInfo[]
  count: number
  pageIndex: number
  openDetail: (content: string) => void
}> = props => {
  const { type = 'business', listData, count, pageIndex, openDetail } = props

  const { onChangeTab: onChangeTabHandler, onChangePageIndex } =
    useTableContext()
  /** 是否接听 -1：全部 0：未接听 1：已接听 */
  const [activeTab, setActiveTab] = useState<keyof typeof Tab_status>('all')
  // const [listData, setListData] = useState<P1AlarmInfo[]>(tableList)
  const tableWrapRef = useRef<HTMLDivElement>(null)
  const [maxCount, setMaxCount] = useState<number>(11)

  // 获取状态标签配置
  const getStatusTag = (status: P1AlarmInfo['phoneAnsweredFlag']) => {
    if (status === 1) {
      return (
        <Tag
          icon={<CheckCircleOutlined />}
          color="success"
          className={`${styles.statusTag} ${styles.connected}`}
        >
          已接通
        </Tag>
      )
    }
    return (
      <Tag
        icon={<CloseCircleOutlined />}
        color="error"
        className={`${styles.statusTag} ${styles.disconnected}`}
      >
        未接通
      </Tag>
    )
  }

  // 获取告警级别标签
  const getLevelTag = (level: 'high' | 'medium' | 'low') => {
    const levelConfig = {
      high: { text: '高危', icon: <ExclamationCircleOutlined /> },
      medium: { text: '中等', icon: <ExclamationCircleOutlined /> },
      low: { text: '低危', icon: <ExclamationCircleOutlined /> },
    }

    const config = levelConfig[level]
    return (
      <Tag icon={config.icon} className={`${styles.levelTag} ${styles[level]}`}>
        {config.text}
      </Tag>
    )
  }
  function onChangeTab(key: string) {
    const curKey = key as keyof typeof Tab_status
    setActiveTab(curKey)
    onChangeTabHandler(type, key)
  }
  function onCheckDetail(content: string) {
    console.log('onCheckDetail', content)
    openDetail(content)
  }

  function onChangePage(page: number, pageSize: number) {
    console.log('onChangePageIndex', page, pageSize)
    onChangePageIndex(type, page)
  }
  // 表格列配置
  const columns: ColumnsType<P1AlarmInfo> = [
    {
      title: '告警时间',
      dataIndex: 'sendDate',
      width: '15%',
      render: (time: string) => <span className={styles.timeCell}>{time}</span>,
    },
    {
      title: '告警标题',
      dataIndex: 'alarmTitle',
      width: '30%',
      render: (title: string) => (
        <span className={styles.titleCell}>{title}</span>
      ),
    },
    {
      title: '内容',
      dataIndex: 'alarmContent',
      render: (alarmContent: string, record: P1AlarmInfo) => (
        <Typography.Link
          className={`${styles.titleCell} w-[300px] block text-ellipsis whitespace-nowrap overflow-hidden`}
          type={`${record.phoneAnsweredFlag == 1 ? 'success' : 'danger'}`}
          underline
          onClick={() => onCheckDetail(alarmContent)}
        >
          {alarmContent}
        </Typography.Link>
      ),
    },
    {
      title: '通知人员',
      dataIndex: 'dueName',
      width: '20%',
      render: (dueName: string, record: P1AlarmInfo) => (
        <Space className={styles.notifierCell}>
          <PhoneOutlined className={styles.phoneIcon} />
          <span>
            {dueName} - {record.duePhoneNo}
          </span>
        </Space>
      ),
    },
    {
      title: '接通状态',
      dataIndex: 'phoneAnsweredFlag',
      width: '20%',
      render: (phoneAnsweredFlag: P1AlarmInfo['phoneAnsweredFlag']) =>
        getStatusTag(phoneAnsweredFlag),
    },
  ]

  return (
    <Card className={`panel ${styles.alertListContainer}`}>
      {/* 标题区域 */}
      <Title
        level={4}
        className={`${styles.title} flex items-center justify-between`}
      >
        <div className="flex items-center">
          <div className={styles.titleIcon} />
          {type === 'business' ? '业务监控' : '运维监控'}
        </div>
        {count > 0 && (
          <Pagination
            style={{ marginBottom: 0 }}
            size="small"
            showQuickJumper
            showSizeChanger={false}
            showTotal={total => `共 ${total} 条`}
            total={count}
            current={pageIndex}
            onChange={onChangePage}
          />
        )}
      </Title>
      {/* 标签页区域 */}
      <div className={styles.tabsSection}>
        <Tabs
          activeKey={activeTab}
          onChange={onChangeTab}
          size="middle"
          items={[
            {
              key: 'all',
              label: (
                <span
                  className={`${styles.tabLabel} ${activeTab === 'all' ? styles.active : styles.inactive}`}
                >
                  全部
                </span>
              ),
            },
            {
              key: 'disconnected',
              label: (
                <span
                  className={`${styles.tabLabel} ${activeTab === 'disconnected' ? styles.active : styles.inactive}`}
                >
                  未接通
                </span>
              ),
            },
            {
              key: 'connected',
              label: (
                <span
                  className={`${styles.tabLabel} ${activeTab === 'connected' ? styles.active : styles.inactive}`}
                >
                  已接通
                </span>
              ),
            },
          ]}
          // tabBarExtraContent={
          //   <div className="h-full flex items-center">
          //     <Input placeholder="请输入操作人" size="small" />
          //   </div>
          // }
        />
      </div>

      {/* 表格区域 */}
      <div className={styles.tableSection} ref={tableWrapRef}>
        <Table<P1AlarmInfo>
          rowKey="id"
          columns={columns}
          dataSource={listData}
          pagination={false}
          size="small"
          bordered={false}
          rowClassName={(record, index) =>
            index % 2 === 0 ? 'table-row-even' : 'table-row-odd'
          }
        />
      </div>
    </Card>
  )
}

export default TableList
